﻿using System;
using System.Collections.Generic;
using System.Linq;

using System.Web.Mvc;
using SimpleApp.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;  

namespace SimpleApp.Controllers
{
    public class InspireController : Controller
    {
        private SelfInfoEntities SelfInfo = new SelfInfoEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Search(string name=" ")
        {
      
            var res = SelfInfo.INSPIRATION.Where(t => t.NAME.Contains(name) );
            return View(res.ToList<INSPIRATION>());
        }


        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(INSPIRATION item)
        {
            var res = SelfInfo.INSPIRATION.Where(t => t.NAME==item.NAME);
            if (res.Count<INSPIRATION>() > 0) {
                return View(item);
            }
            if (ModelState.IsValid)
            {
                item.CREATEDATE = System.DateTime.Now;
                SelfInfo.INSPIRATION.Add(item);
                SelfInfo.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(item);

        }


        public JsonResult GetInspire()
        {
            var res = new JsonResult();  
            using (var db = new SelfInfoEntities())
            {
                List<INSPIRATION> inslist = db.INSPIRATION.ToList();
                var jsonList = JsonConvert.SerializeObject(inslist);
                return Json(jsonList, JsonRequestBehavior.AllowGet); 
            }             
        }

        public ActionResult Delete(int id)
        {
            INSPIRATION item = SelfInfo.INSPIRATION.Where(t => t.ID == id).First<INSPIRATION>();
            if (ModelState.IsValid)
            {
                string name = item.NAME;
                SelfInfo.INSPIRATION.Remove(item);
                SelfInfo.SaveChanges();
                return RedirectToAction("Search", new { name = name });
            }
            return View(item);
        }
    }
}
